/**
 * 24点数学挑战游戏
 * 核心游戏逻辑与界面交互
 */

// DOM元素
const gameContainer = document.getElementById('game-container');
const welcomeScreen = document.getElementById('welcome-screen');
const gamePlay = document.getElementById('game-play');
const gameResult = document.getElementById('game-result');
const startBtn = document.getElementById('start-btn');
const rulesBtn = document.getElementById('rules-btn');
const tutorialOverlay = document.getElementById('tutorial-overlay');
const closeTutorialBtn = document.getElementById('close-tutorial');
const startFromTutorialBtn = document.getElementById('start-from-tutorial');
const cardsContainer = document.getElementById('cards-container');
const expressionDisplay = document.getElementById('expression-display');
const calculateBtn = document.getElementById('calculate-btn');
const timerDisplay = document.getElementById('timer-display');
const scoreDisplay = document.getElementById('score-display');
const hintBtn = document.getElementById('hint-btn');
const undoBtn = document.getElementById('undo-btn');
const newGameBtn = document.getElementById('new-game-btn');
const successResult = document.getElementById('success-result');
const failureResult = document.getElementById('failure-result');
const timeValue = document.getElementById('time-value');
const movesValue = document.getElementById('moves-value');
const continueBtn = document.getElementById('continue-btn');
const retryBtn = document.getElementById('retry-btn');
const nextChallengeBtn = document.getElementById('next-challenge-btn');
const showSolutionBtn = document.getElementById('show-solution-btn');
const solutionDisplay = document.getElementById('solution-display');
const difficultyBtns = document.querySelectorAll('.difficulty-btn');
const opBtns = document.querySelectorAll('.op-btn');
const themeToggle = document.querySelector('.theme-toggle');
const solvedCount = document.getElementById('solved-count');
const bestTime = document.getElementById('best-time');
const streakDays = document.getElementById('streak-days');
const historyData = document.getElementById('history-data');

// 游戏状态
let gameState = {
    cards: [],
    selectedCards: [],
    selectedOp: null,
    currentExpression: null,
    history: [],
    difficulty: 'medium',
    startTime: null,
    timerInterval: null,
    elapsedSeconds: 0,
    moves: 0,
    solutions: [],
    isDarkMode: false,
    gameActive: false
};

// 游戏统计数据
let gameStats = {
    solved: 0,
    bestTime: Infinity,
    streak: 0,
    lastPlayed: null,
    history: []
};

// 初始化
function init() {
    loadStats();
    updateStatsDisplay();
    updateHistoryTable();
    
    // 事件监听器
    startBtn.addEventListener('click', startGame);
    rulesBtn.addEventListener('click', showTutorial);
    closeTutorialBtn.addEventListener('click', hideTutorial);
    startFromTutorialBtn.addEventListener('click', () => {
        hideTutorial();
        startGame();
    });
    
    calculateBtn.addEventListener('click', performCalculation);
    hintBtn.addEventListener('click', showHint);
    undoBtn.addEventListener('click', undoLastMove);
    newGameBtn.addEventListener('click', resetGame);
    
    continueBtn.addEventListener('click', nextChallenge);
    retryBtn.addEventListener('click', retryChallenge);
    nextChallengeBtn.addEventListener('click', nextChallenge);
    showSolutionBtn.addEventListener('click', toggleSolution);
    
    difficultyBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            difficultyBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            gameState.difficulty = btn.dataset.difficulty;
        });
    });
    
    opBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            if (!gameState.gameActive) return;
            
            if (gameState.selectedCards.length !== 2) {
                showToast('请先选择两个数字', 'warning');
                return;
            }
            
            selectOperator(btn);
        });
    });
    
    themeToggle.addEventListener('click', toggleTheme);
    
    // 默认选择中等难度
    document.querySelector('[data-difficulty="medium"]').classList.add('active');
    
    // 检查主题偏好
    checkThemePreference();
    
    // 检查连续游戏记录
    checkStreak();
}

// 加载统计数据
function loadStats() {
    const savedStats = localStorage.getItem('game24_stats');
    if (savedStats) {
        gameStats = JSON.parse(savedStats);
    }
}

// 保存统计数据
function saveStats() {
    localStorage.setItem('game24_stats', JSON.stringify(gameStats));
}

// 更新统计显示
function updateStatsDisplay() {
    solvedCount.textContent = gameStats.solved || 0;
    bestTime.textContent = gameStats.bestTime !== Infinity ? formatTime(gameStats.bestTime) : '--:--';
    streakDays.textContent = gameStats.streak || 0;
}

// 更新历史记录表
function updateHistoryTable() {
    historyData.innerHTML = '';
    
    if (!gameStats.history || gameStats.history.length === 0) {
        const emptyRow = document.createElement('tr');
        emptyRow.innerHTML = `<td colspan="4" class="text-center">暂无记录</td>`;
        historyData.appendChild(emptyRow);
        return;
    }
    
    // 只显示最近10条记录
    const recentHistory = gameStats.history.slice(-10).reverse();
    
    recentHistory.forEach(record => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${formatDate(record.date)}</td>
            <td>${record.numbers.join(', ')}</td>
            <td>${formatTime(record.time)}</td>
            <td>
                <button class="replay-btn" data-numbers="${record.numbers.join(',')}" title="重新挑战">
                    <i class="fas fa-play"></i>
                </button>
            </td>
        `;
        historyData.appendChild(row);
    });
    
    // 添加重玩按钮事件
    document.querySelectorAll('.replay-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const numbers = btn.dataset.numbers.split(',').map(Number);
            startGameWithNumbers(numbers);
        });
    });
}

// 检查主题偏好
function checkThemePreference() {
    const darkMode = localStorage.getItem('game24_darkMode') === 'true';
    if (darkMode) {
        document.body.classList.add('dark-theme');
        gameState.isDarkMode = true;
        themeToggle.innerHTML = '<i class="fas fa-sun"></i>';
    }
}

// 切换主题
function toggleTheme() {
    document.body.classList.toggle('dark-theme');
    gameState.isDarkMode = !gameState.isDarkMode;
    
    if (gameState.isDarkMode) {
        themeToggle.innerHTML = '<i class="fas fa-sun"></i>';
    } else {
        themeToggle.innerHTML = '<i class="fas fa-moon"></i>';
    }
    
    localStorage.setItem('game24_darkMode', gameState.isDarkMode);
}

// 检查连续游戏天数
function checkStreak() {
    const today = new Date().toLocaleDateString();
    
    if (!gameStats.lastPlayed) {
        gameStats.streak = 0;
        return;
    }
    
    const lastPlayed = new Date(gameStats.lastPlayed);
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    
    if (lastPlayed.toLocaleDateString() === yesterday.toLocaleDateString()) {
        // 昨天玩过，维持streak
    } else if (lastPlayed.toLocaleDateString() !== today) {
        // 不是昨天也不是今天，重置streak
        gameStats.streak = 0;
    }
    
    saveStats();
    updateStatsDisplay();
}

// 更新连续天数
function updateStreak() {
    const today = new Date().toLocaleDateString();
    
    if (gameStats.lastPlayed !== today) {
        gameStats.lastPlayed = today;
        gameStats.streak += 1;
        saveStats();
        updateStatsDisplay();
    }
}

// 显示教程
function showTutorial() {
    tutorialOverlay.style.display = 'flex';
    tutorialOverlay.classList.add('animate-fadeIn');
}

// 隐藏教程
function hideTutorial() {
    tutorialOverlay.style.display = 'none';
}

// 开始游戏
function startGame() {
    welcomeScreen.style.display = 'none';
    gamePlay.style.display = 'block';
    gameResult.style.display = 'none';
    
    // 初始化游戏状态
    resetGameState();
    
    // 生成数字卡片
    generateNumberCards();
    
    // 查找所有可能解
    findAllSolutions();
    
    // 开始计时
    startTimer();
    
    gameState.gameActive = true;
    
    // 更新连续天数
    updateStreak();
}

// 使用指定数字开始游戏
function startGameWithNumbers(numbers) {
    welcomeScreen.style.display = 'none';
    gamePlay.style.display = 'block';
    gameResult.style.display = 'none';
    
    // 初始化游戏状态
    resetGameState();
    
    // 设置指定的数字
    gameState.cards = numbers.map(num => ({ value: num, isSelected: false, id: Math.random().toString(36).substring(2, 9) }));
    
    // 渲染卡片
    renderCards();
    
    // 查找所有可能解
    findAllSolutions();
    
    // 开始计时
    startTimer();
    
    gameState.gameActive = true;
    
    // 更新连续天数
    updateStreak();
}

// 重置游戏状态
function resetGameState() {
    gameState.cards = [];
    gameState.selectedCards = [];
    gameState.selectedOp = null;
    gameState.currentExpression = null;
    gameState.history = [];
    gameState.startTime = new Date();
    gameState.elapsedSeconds = 0;
    gameState.moves = 0;
    gameState.solutions = [];
    
    // 重置UI
    cardsContainer.innerHTML = '';
    expressionDisplay.textContent = '选择两个数字和一个运算符';
    calculateBtn.disabled = true;
    undoBtn.disabled = true;
    
    // 清除所有选中的运算符
    opBtns.forEach(btn => btn.classList.remove('selected'));
    
    // 重置计时器
    clearInterval(gameState.timerInterval);
    timerDisplay.textContent = '00:00';
    
    // 重置得分
    scoreDisplay.textContent = '0';
}

// 根据难度级别生成数字卡片
function generateNumberCards() {
    let numbers = [];
    
    // 根据难度生成数字
    switch(gameState.difficulty) {
        case 'easy':
            // 简单模式：数字小，容易组合
            numbers = generateEasyNumbers();
            break;
        case 'hard':
            // 困难模式：需要更复杂的计算
            numbers = generateHardNumbers();
            break;
        case 'medium':
        default:
            // 中等模式：平衡难度
            numbers = generateMediumNumbers();
            break;
    }
    
    gameState.cards = numbers.map(num => ({
        value: num,
        isSelected: false,
        id: Math.random().toString(36).substring(2, 9)
    }));
    
    renderCards();
}

// 生成简单难度数字
function generateEasyNumbers() {
    // 简单模式下，生成更容易计算得到24的数字
    // 例如：3,8,3,1 (3*8*1=24) 或 4,6,1,4 ((4+4)*6/1=48)
    const easyPools = [
        [1, 2, 3, 8],
        [1, 3, 4, 6],
        [2, 2, 6, 4],
        [1, 4, 6, 4],
        [2, 4, 4, 3],
        [3, 3, 4, 2],
        [6, 6, 2, 1],
        [1, 8, 3, 1]
    ];
    
    // 随机选择一组
    return easyPools[Math.floor(Math.random() * easyPools.length)];
}

// 生成中等难度数字
function generateMediumNumbers() {
    // 使用最常见的24点组合，但会包含一些需要复杂运算的组合
    const numbers = [];
    
    // 生成4个1-13的随机数字
    for (let i = 0; i < 4; i++) {
        numbers.push(Math.floor(Math.random() * 13) + 1);
    }
    
    return numbers;
}

// 生成困难难度数字
function generateHardNumbers() {
    // 困难模式，生成需要更复杂计算的数字组合
    const hardPools = [
        [5, 5, 5, 1],
        [13, 11, 7, 1],
        [13, 10, 4, 1],
        [12, 12, 6, 1],
        [3, 3, 8, 8],
        [9, 9, 9, 6],
        [7, 7, 3, 3],
        [11, 11, 2, 2]
    ];
    
    // 随机选择一组
    return hardPools[Math.floor(Math.random() * hardPools.length)];
}

// 渲染卡片
function renderCards() {
    cardsContainer.innerHTML = '';
    
    gameState.cards.forEach(card => {
        const cardElement = document.createElement('div');
        cardElement.className = `number-card ${card.isSelected ? 'selected' : ''}`;
        cardElement.dataset.id = card.id;
        cardElement.textContent = card.value;
        
        // 添加点击事件
        cardElement.addEventListener('click', () => {
            if (!gameState.gameActive) return;
            
            toggleCardSelection(card);
        });
        
        cardsContainer.appendChild(cardElement);
    });
}

// 切换卡片选择状态
function toggleCardSelection(card) {
    // 如果卡片已经被选中，则取消选择
    if (card.isSelected) {
        card.isSelected = false;
        gameState.selectedCards = gameState.selectedCards.filter(c => c.id !== card.id);
    } else {
        // 如果已经选了两张卡，不能再选更多
        if (gameState.selectedCards.length >= 2) {
            showToast('最多只能选择两张卡片', 'warning');
            return;
        }
        
        card.isSelected = true;
        gameState.selectedCards.push(card);
    }
    
    // 更新表达式显示
    updateExpressionDisplay();
    
    // 更新卡片UI
    renderCards();
    
    // 如果选择了两张卡片，可以选择运算符
    if (gameState.selectedCards.length === 2 && gameState.selectedOp) {
        calculateBtn.disabled = false;
    } else {
        calculateBtn.disabled = true;
        // 如果没有选两张卡，也重置操作符选择
        if (gameState.selectedCards.length !== 2) {
            resetOperatorSelection();
        }
    }
}

// 选择运算符
function selectOperator(btn) {
    // 重置所有运算符按钮的样式
    opBtns.forEach(b => b.classList.remove('selected'));
    
    // 设置当前选中的运算符
    btn.classList.add('selected');
    gameState.selectedOp = btn.dataset.operation;
    
    // 更新表达式显示
    updateExpressionDisplay();
    
    // 启用计算按钮
    calculateBtn.disabled = false;
}

// 重置运算符选择
function resetOperatorSelection() {
    opBtns.forEach(btn => btn.classList.remove('selected'));
    gameState.selectedOp = null;
    calculateBtn.disabled = true;
}

// 更新表达式显示
function updateExpressionDisplay() {
    if (gameState.selectedCards.length === 0) {
        expressionDisplay.textContent = '选择两个数字和一个运算符';
        return;
    }
    
    let expression = '';
    
    if (gameState.selectedCards.length >= 1) {
        expression += gameState.selectedCards[0].value;
    }
    
    if (gameState.selectedOp && gameState.selectedCards.length >= 1) {
        expression += ' ' + gameState.selectedOp + ' ';
    }
    
    if (gameState.selectedCards.length >= 2) {
        expression += gameState.selectedCards[1].value;
    }
    
    if (gameState.selectedCards.length === 2 && gameState.selectedOp) {
        expression += ' = ?';
    }
    
    gameState.currentExpression = expression;
    expressionDisplay.textContent = expression;
}

// 执行计算
function performCalculation() {
    if (gameState.selectedCards.length !== 2 || !gameState.selectedOp) {
        showToast('请选择两个数字和一个运算符', 'warning');
        return;
    }
    
    const num1 = gameState.selectedCards[0].value;
    const num2 = gameState.selectedCards[1].value;
    const op = gameState.selectedOp;
    
    let result;
    let isValidOperation = true;
    
    // 计算结果
    switch(op) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '×':
            result = num1 * num2;
            break;
        case '÷':
            if (num2 === 0) {
                showToast('除数不能为零', 'error');
                isValidOperation = false;
                return;
            }
            // 检查除法是否有余数
            if (num1 % num2 !== 0) {
                showToast('除法运算结果必须是整数', 'warning');
                isValidOperation = false;
                return;
            }
            result = num1 / num2;
            break;
    }
    
    if (!isValidOperation) return;
    
    // 保存此步骤的历史记录
    const historyStep = {
        expression: `${num1} ${op} ${num2} = ${result}`,
        cards: [...gameState.cards],
        selectedCards: [...gameState.selectedCards]
    };
    
    gameState.history.push(historyStep);
    
    // 增加移动步数
    gameState.moves++;
    
    // 从原数组中移除已选卡片
    const selectedIds = gameState.selectedCards.map(card => card.id);
    gameState.cards = gameState.cards.filter(card => !selectedIds.includes(card.id));
    
    // 添加计算结果卡片
    const resultCard = {
        value: result,
        isSelected: false,
        id: Math.random().toString(36).substring(2, 9),
        isResult: true
    };
    
    gameState.cards.push(resultCard);
    
    // 重置选择状态
    gameState.selectedCards = [];
    resetOperatorSelection();
    
    // 渲染卡片
    renderCards();
    
    // 更新表达式显示
    expressionDisplay.textContent = `${num1} ${op} ${num2} = ${result}`;
    
    // 启用撤销按钮
    undoBtn.disabled = false;
    
    // 检查游戏是否结束
    if (gameState.cards.length === 1) {
        checkResult();
    } else {
        // 更新分数
        updateScore();
    }
}

// 撤销上一步操作
function undoLastMove() {
    if (gameState.history.length === 0) {
        showToast('没有可撤销的操作', 'warning');
        return;
    }
    
    // 获取最后一步操作
    const lastStep = gameState.history.pop();
    
    // 恢复卡片状态
    gameState.cards = lastStep.cards;
    gameState.selectedCards = [];
    resetOperatorSelection();
    
    // 重新渲染卡片
    renderCards();
    
    // 更新表达式显示
    expressionDisplay.textContent = '选择两个数字和一个运算符';
    
    // 如果没有历史记录了，禁用撤销按钮
    if (gameState.history.length === 0) {
        undoBtn.disabled = true;
    }
    
    // 减少移动步数
    gameState.moves--;
    
    // 更新分数
    updateScore();
}

// 显示提示
function showHint() {
    if (gameState.solutions.length === 0) {
        showToast('找不到合适的解法提示', 'warning');
        return;
    }
    
    // 随机选择一个解法
    const solution = gameState.solutions[0];
    
    showToast(`提示: 尝试 ${solution}`, 'info', 5000);
}

// 检查游戏结果
function checkResult() {
    clearInterval(gameState.timerInterval);
    gameState.gameActive = false;
    
    const finalValue = gameState.cards[0].value;
    
    if (finalValue === 24) {
        // 成功
        gameResult.style.display = 'block';
        successResult.style.display = 'block';
        failureResult.style.display = 'none';
        gamePlay.style.display = 'none';
        
        // 记录时间和步数
        timeValue.textContent = formatTime(gameState.elapsedSeconds);
        movesValue.textContent = `${gameState.moves}步`;
        
        // 更新游戏统计
        gameStats.solved++;
        
        if (gameState.elapsedSeconds < gameStats.bestTime) {
            gameStats.bestTime = gameState.elapsedSeconds;
        }
        
        // 记录游戏历史
        const historyEntry = {
            date: new Date().toISOString(),
            numbers: gameState.history[0].cards.map(card => card.value),
            time: gameState.elapsedSeconds,
            solved: true,
            moves: gameState.moves
        };
        
        if (!gameStats.history) {
            gameStats.history = [];
        }
        
        gameStats.history.push(historyEntry);
        
        // 保存统计数据
        saveStats();
        updateStatsDisplay();
        updateHistoryTable();
        
    } else {
        // 失败
        gameResult.style.display = 'block';
        successResult.style.display = 'none';
        failureResult.style.display = 'block';
        gamePlay.style.display = 'none';
        
        // 隐藏解法显示
        solutionDisplay.style.display = 'none';
    }
}

// 显示解法
function toggleSolution() {
    if (solutionDisplay.style.display === 'none') {
        if (gameState.solutions.length > 0) {
            solutionDisplay.textContent = gameState.solutions.join('\n');
            solutionDisplay.style.display = 'block';
            showSolutionBtn.textContent = '隐藏解法';
        } else {
            solutionDisplay.textContent = '无解';
            solutionDisplay.style.display = 'block';
            showSolutionBtn.textContent = '隐藏';
        }
    } else {
        solutionDisplay.style.display = 'none';
        showSolutionBtn.textContent = '查看解法';
    }
}

// 找到所有可能的24点解法
function findAllSolutions() {
    const numbers = gameState.cards.map(card => card.value);
    gameState.solutions = find24(numbers);
}

// 24点算法
function find24(nums) {
    const solutions = [];
    const ops = ['+', '-', '*', '/'];
    
    function generateExpressions(numbers) {
        if (numbers.length === 1) {
            // 如果结果是24，则找到一个解
            if (Math.abs(numbers[0] - 24) < 0.0001) {
                return [numbers[0].toString()];
            }
            return [];
        }
        
        const expressions = [];
        
        // 尝试所有可能的数字对组合
        for (let i = 0; i < numbers.length; i++) {
            for (let j = i + 1; j < numbers.length; j++) {
                const a = numbers[i];
                const b = numbers[j];
                
                // 创建一个新数组，不包含a和b
                const newNumbers = numbers.filter((_, index) => index !== i && index !== j);
                
                // 尝试所有运算符
                for (const op of ops) {
                    // 避免除以零
                    if (op === '/' && (b === 0 || a % b !== 0)) continue;
                    
                    // 计算a op b
                    let result;
                    let expression;
                    switch (op) {
                        case '+':
                            result = a + b;
                            expression = `(${a} + ${b})`;
                            break;
                        case '-':
                            result = a - b;
                            expression = `(${a} - ${b})`;
                            break;
                        case '*':
                            result = a * b;
                            expression = `(${a} × ${b})`;
                            break;
                        case '/':
                            result = a / b;
                            expression = `(${a} ÷ ${b})`;
                            break;
                    }
                    
                    // 递归计算剩余数字
                    const nextNumbers = [...newNumbers, result];
                    const remainingExpressions = generateExpressions(nextNumbers);
                    
                    // 如果找到解，将表达式添加到solutions
                    remainingExpressions.forEach(expr => {
                        const fullExpr = expr.replace(result.toString(), expression);
                        expressions.push(fullExpr);
                    });
                    
                    // 对于非对称操作，尝试反向操作 (b op a)
                    if (op === '-' || op === '/') {
                        // 避免除以零
                        if (op === '/' && (a === 0 || b % a !== 0)) continue;
                        
                        let reverseResult;
                        let reverseExpression;
                        switch (op) {
                            case '-':
                                reverseResult = b - a;
                                reverseExpression = `(${b} - ${a})`;
                                break;
                            case '/':
                                reverseResult = b / a;
                                reverseExpression = `(${b} ÷ ${a})`;
                                break;
                        }
                        
                        // 递归计算剩余数字
                        const reverseNextNumbers = [...newNumbers, reverseResult];
                        const reverseRemainingExpressions = generateExpressions(reverseNextNumbers);
                        
                        // 如果找到解，将表达式添加到solutions
                        reverseRemainingExpressions.forEach(expr => {
                            const fullExpr = expr.replace(reverseResult.toString(), reverseExpression);
                            expressions.push(fullExpr);
                        });
                    }
                }
            }
        }
        
        return expressions;
    }
    
    return generateExpressions(nums);
}

// 重试当前挑战
function retryChallenge() {
    // 获取原始数字
    const originalNumbers = gameState.history.length > 0 && gameState.history[0].cards 
        ? gameState.history[0].cards.map(card => card.value) 
        : generateMediumNumbers();
    
    startGameWithNumbers(originalNumbers);
}

// 开始下一个挑战
function nextChallenge() {
    startGame();
}

// 重置游戏
function resetGame() {
    // 提示用户确认
    if (confirm('确定要重新开始游戏吗？当前进度将不会保存。')) {
        startGame();
    }
}

// 开始计时器
function startTimer() {
    gameState.startTime = new Date();
    gameState.elapsedSeconds = 0;
    timerDisplay.textContent = '00:00';
    
    clearInterval(gameState.timerInterval);
    
    gameState.timerInterval = setInterval(() => {
        const now = new Date();
        gameState.elapsedSeconds = Math.floor((now - gameState.startTime) / 1000);
        timerDisplay.textContent = formatTime(gameState.elapsedSeconds);
    }, 1000);
}

// 格式化时间显示
function formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// 格式化日期显示
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString();
}

// 更新分数
function updateScore() {
    // 简单计分方式：步数越少，分数越高
    const baseScore = 1000;
    const movePenalty = 50;
    const timePenalty = 2;
    
    let score = baseScore - (gameState.moves * movePenalty) - (gameState.elapsedSeconds * timePenalty);
    score = Math.max(0, score); // 确保分数不为负
    
    scoreDisplay.textContent = score;
}

// 显示提示消息
function showToast(message, type = 'info', duration = 3000) {
    // 检查是否已存在toast容器
    let toastContainer = document.querySelector('.toast-container');
    
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.className = 'toast-container';
        document.body.appendChild(toastContainer);
        
        // 添加样式
        const style = document.createElement('style');
        style.textContent = `
            .toast-container {
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 9999;
            }
            .toast {
                padding: 12px 20px;
                margin-bottom: 10px;
                border-radius: 4px;
                color: white;
                box-shadow: 0 3px 10px rgba(0,0,0,0.2);
                display: flex;
                align-items: center;
                transform: translateX(100%);
                animation: slideIn 0.3s forwards, fadeOut 0.3s forwards;
                animation-delay: 0s, var(--duration);
            }
            .toast.info { background-color: var(--primary-color); }
            .toast.success { background-color: var(--success-color); }
            .toast.warning { background-color: var(--warning-color); }
            .toast.error { background-color: var(--error-color); }
            
            .toast i {
                margin-right: 10px;
            }
            
            @keyframes slideIn {
                to { transform: translateX(0); }
            }
            @keyframes fadeOut {
                to { opacity: 0; transform: translateX(100%); }
            }
        `;
        document.head.appendChild(style);
    }
    
    // 创建toast
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.style.setProperty('--duration', `${duration/1000 - 0.3}s`);
    
    // 设置图标
    let icon = '';
    switch(type) {
        case 'info': icon = '<i class="fas fa-info-circle"></i>'; break;
        case 'success': icon = '<i class="fas fa-check-circle"></i>'; break;
        case 'warning': icon = '<i class="fas fa-exclamation-triangle"></i>'; break;
        case 'error': icon = '<i class="fas fa-times-circle"></i>'; break;
    }
    
    toast.innerHTML = `${icon}${message}`;
    toastContainer.appendChild(toast);
    
    // 自动移除
    setTimeout(() => {
        toast.remove();
    }, duration);
}

// 初始化游戏
document.addEventListener('DOMContentLoaded', init); 